<template>
  <div class="video-container">
    <!-- <input
      type="hidden"
      name="webrtc-url"
      id="webrtc-url"
      value="http://localhost:8183/stream/172.16.0.241/channel/33/webrtc"
    /> -->
    <video
      ref="videoEl"
      autoplay
      muted
      playsinline
      controls
      style="max-width: 100%; max-height: 100%"
    ></video>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";

const props = defineProps({
  webrtcUrl: String,
});

const videoEl = ref(null);
// const webrtcUrl = ref(
//   "http://localhost:8183/stream/172.16.0.241/channel/33/webrtc"
// );

const webrtcUrl = ref(props.webrtcUrl);

const startPlay = (videoEl, url) => {
  const webrtc = new RTCPeerConnection({
    iceServers: [
      {
        urls: ["stun:stun.l.google.com:19302"],
      },
    ],
    sdpSemantics: "unified-plan",
  });

  webrtc.ontrack = function (event) {
    console.log(event.streams.length + " track is delivered");
    videoEl.srcObject = event.streams[0];
    videoEl.play();
  };

  webrtc.addTransceiver("video", { direction: "sendrecv" });

  webrtc.onnegotiationneeded = async function handleNegotiationNeeded() {
    const offer = await webrtc.createOffer();
    await webrtc.setLocalDescription(offer);

    fetch(url, {
      method: "POST",
      body: new URLSearchParams({ data: btoa(webrtc.localDescription.sdp) }),
    })
      .then((response) => response.text())
      .then((data) => {
        try {
          webrtc.setRemoteDescription(
            new RTCSessionDescription({ type: "answer", sdp: atob(data) })
          );
        } catch (e) {
          console.warn(e);
        }
      });
  };

  const webrtcSendChannel = webrtc.createDataChannel("rtsptowebSendChannel");

  webrtcSendChannel.onopen = () => {
    console.log(`${webrtcSendChannel.label} has opened`);
    webrtcSendChannel.send("ping");
  };

  webrtcSendChannel.onclose = () => {
    console.log(`${webrtcSendChannel.label} has closed`);
    startPlay(videoEl, url);
  };

  webrtcSendChannel.onmessage = (event) => console.log(event.data);
};

onMounted(() => {
  startPlay(videoEl.value, webrtcUrl.value);
});
</script>

<script>
export default {
  name: "WebVideo",
};
</script>

<style scoped>
video {
  max-width: 100%;
  max-height: 100%;
}
</style>
